package com.lagou.flink.work.p1;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.util.Collector;
import scala.Tuple2;

/**
 * 功能描述：作业1
 *
 * @author : zhangyong
 * @since : 2021/5/18
 */
public class Work1 {

    public static void main(String[] args) throws Exception {
        String inputStr = args[0];
        String outputStr = args[1];
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        DataSet<String> textInfo = env.readTextFile(inputStr);
        DataSet<Tuple2<String, Integer>> sumDs = textInfo.flatMap(new LineSplitter()).groupBy(0).sum(1);
        sumDs.writeAsCsv(outputStr,"\n","").setParallelism(1);
        env.execute();
    }

    static class LineSplitter implements FlatMapFunction<String,
            Tuple2<String,Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            for (String word : s.split(" ")) {
                collector.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
